//
//  SingleViewController.m
//  OpenYourEyes
//
//  Created by zhanglei on 15/8/13.
//  Copyright (c) 2015年 zhanglei. All rights reserved.
//

#define SIMPLE_SAMPLE NO

#import "SingleViewController.h"
#import "Header.h"
#import "BaseButtonVIew.h"
#import "BTGlassScrollView.h"
#import "DownSideView.h"
#import "TotalFiveScrollView.h"
#import "MuchScrollView.h"
#import "MoviePlayerViewController.h"
#import "VideoPlayerViewController.h"
#import "FMDatabase.h"
#import "AFHTTPRequestOperation.h"

@interface SingleViewController ()<tapToDownload>

//上半部分scrollview
@property (nonatomic,strong)MuchScrollView *viewScroll;
//下半部分的view
@property (nonatomic,strong)DownSideView *downsideView;

@property (nonatomic,strong)UIView* scrollFootView;

@property (nonatomic,strong)UILabel *pageNumberLabel;

@property (nonatomic,strong)UIImageView *pageNumberWhiteLine;
//给scrollview的图片一个button用来跳转播放
@property (nonatomic,strong)UIButton *centerButton;
//收藏按钮
@property (nonatomic, strong)UIButton *collectionButton;
//收藏label
@property (nonatomic, strong)UILabel *collectionLabel;
//缓存下载按钮
@property (nonatomic, strong)UIButton *playButton;
//缓存下载Label
@property (nonatomic, strong)UILabel *playLabel;

@property (nonatomic, strong) UIButton *btnDownload;
//  数据库表
@property (nonatomic, strong)FMDatabase *db;

@property (nonatomic, strong)NSURLRequest * request;

@property (nonatomic, strong)AFHTTPRequestOperation *operation;

@property (nonatomic, strong) NSMutableArray * dataArray;

@property (nonatomic, assign) BOOL isCollect;  //  判断是否收藏



@end

@implementation SingleViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self createFirstView];
    
    [self createTheBigImageView];
    
    [self createTwoButton];
    
    [self isCollection];
    
    [self isDownload];
    
}

//懒加载
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        self.dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)createTheBigImageView
{
    _viewScroll = [[MuchScrollView alloc]initWithFrame:CGRectMake(0 ,0, self.view.frame.size.width, self.view.frame.size.height)];
    
    _viewScroll.model = _model;
    
    [self.view addSubview:_viewScroll];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    
    [_viewScroll.scrollView addGestureRecognizer:tap];
    
}

- (void)tapAction:(UIGestureRecognizer *)sender
{
    NSLog(@"点击跳转播放");
    
    VideoPlayerViewController *_modelVC = [[VideoPlayerViewController alloc] init];
    if ([[NSFileManager defaultManager] fileExistsAtPath:[self IsExistdownLoadFilePath]])
    {
        NSURL *url = [NSURL fileURLWithPath:[self IsExistdownLoadFilePath]];
        _modelVC.url = url;
    } else
    {
        _modelVC.url = [NSURL URLWithString:_model.playUrl];
    }
    _modelVC.delegate = self;
    
    _modelVC.model = _model;
    [self presentViewController:_modelVC animated:YES completion:nil];
    
}

#pragma park - 执行代理中的方法
- (void)doTapTotalScrollViewDownloadButton
{
    [self bbb:_btnDownload];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationItem.title = _model.title;
    
    if (!SIMPLE_SAMPLE)
    {
        _centerButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        _centerButton.frame = CGRectMake(SCREEN_WIDTH / 2 - 25 ,SCREEN_WIDTH / 2 - 50 , 50  , 50);
        
        _centerButton.userInteractionEnabled = NO;
        
        [_centerButton setImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
        
        [self.view addSubview:_centerButton];
    }
    [_downsideView startOutPut];
    
}

//添加两个按钮(收藏与下载)
- (void)createTwoButton
{
    //为了自适应所以取一个会根据屏幕宽度不同而不同的值
    CGFloat ten = SCREEN_WIDTH / 48;
    //创建收藏按钮
    _collectionButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _collectionButton.frame = CGRectMake(10, SCREEN_HEIGHT - 22 * ten, 3 * ten, 3 * ten);
    [_collectionButton setImage:[UIImage imageNamed:@"iconfont-weishoucang"] forState:UIControlStateNormal];
    _collectionButton.backgroundColor = [UIColor clearColor];
    [_collectionButton addTarget:self action:@selector(aaa) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_collectionButton];
    //创建收藏按钮旁的Label
    _collectionLabel = [[UILabel alloc]initWithFrame:CGRectMake(5 * ten + 5, SCREEN_HEIGHT - 22 * ten, 15 *ten, 3*ten)];
    _collectionLabel.font = [UIFont systemFontOfSize:14 weight:1];
    _collectionLabel.text = @"收藏";
    _collectionLabel.textColor = [UIColor colorWithWhite:0.900 alpha:1.000];
    [self.view addSubview:_collectionLabel];
    //创建缓存按钮
    _playButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _playButton.frame = CGRectMake(25 * ten, SCREEN_HEIGHT - 22 * ten, 13 * ten, 3 * ten);
    _playButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_playButton setTitle:@"缓存" forState:UIControlStateNormal];
    [_playButton setTintColor:[UIColor whiteColor]];
    [_playButton addTarget:self action:@selector(bbb:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_playButton];
    //创建缓存按钮
    _btnDownload = [UIButton buttonWithType:UIButtonTypeSystem];
    _btnDownload.frame = CGRectMake(24 * ten - 10, SCREEN_HEIGHT - 22 * ten, 3 * ten, 3 * ten);
    [_btnDownload setBackgroundImage:[UIImage imageNamed:@"iconfont-download"] forState:UIControlStateNormal];
    [_btnDownload addTarget:self action:@selector(bbb:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnDownload];
    //创建显示缓存进度的Label
    _playLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_playButton.frame) , SCREEN_HEIGHT - 22 * ten, 15 *ten, 3 * ten)];
    _playLabel.alpha = 0;
    _playLabel.textColor = [UIColor colorWithWhite:0.900 alpha:1.000];
    _playLabel.font = [UIFont systemFontOfSize:14 weight:1];
    [self.view addSubview:_playLabel];
}
/**
 *  判断是否打开数据库
 */
- (void)isWithOpenDataBase
{
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Collection.db"];
    _db = [FMDatabase databaseWithPath:path];
    if (![_db open])
    {
        NSLog(@"数据库打开失败");
        return;
    }
}

- (void)aaa
{
    [self isWithOpenDataBase];
    
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS Collection (Category text, CoverBlurred text, CoverForDetail text, CoverForFeed text, CoverForSharing text, Date integer, Description text, Duration integer, ID integer,Idx integer, PlayUrl text, RawWebUrl text, Title text, WebUrl text)"];
    
    // 在存储之前先进行一次判断 如果数据库已经存储了 就不走下列方法
    //  查询数据库
    FMResultSet *rs = [_db executeQuery:@"SELECT * FROM Collection"];
    while ([rs next])  //  类库中的方法  循环查询
    {
        NSString *title = [rs stringForColumn:@"title"];
        if ([title isEqualToString:_model.title])
        {
            [_collectionButton setImage:[UIImage imageNamed:@"iconfont-weishoucang"] forState:UIControlStateNormal];
            // 同时在数据库中删除删除数据
            [self deleteModelFromDatabase];
            
            int a =  [_model.consumption[@"shareCount"] intValue];
            NSNumber *b = [NSNumber numberWithInt:a];
            NSString *collection = [b stringValue];
            NSString *collectionNew = [NSString stringWithFormat:@"收藏:%@",collection];
            _collectionLabel.text = [NSString stringWithFormat:@"%@",collectionNew];
            
            return;
            
        } else
        {
            
            [_collectionButton setImage:[UIImage imageNamed:@"yishoucang"] forState:UIControlStateNormal];
            int a =  [_model.consumption[@"shareCount"] intValue] + 1;
            NSNumber *b = [NSNumber numberWithInt:a];
            NSString *collection = [b stringValue];
            NSString *collectionNew = [NSString stringWithFormat:@"收藏:%@",collection];
            _collectionLabel.text = [NSString stringWithFormat:@"%@",collectionNew];
            
        }
    }
    [self makeModelToDatabase];
    
}

- (void)bbb:(UIButton *)btn
{
    
    _playLabel.alpha = 1;
    
    if ([_playButton.currentTitle isEqualToString:@"缓存"])
    {
        [_playButton setTitle:@"取消缓存" forState:UIControlStateNormal];
        NSURL * url = [NSURL URLWithString:_model.playUrl];
        self.request = [NSURLRequest requestWithURL:url];
        unsigned long long  downloadedBytes = 0;
        
        //如果存在,说明有缓存文件
        if ([[NSFileManager defaultManager] fileExistsAtPath:[self IsExistFilePath]])
        {
            //计算缓存文件的大小
            downloadedBytes = [self fileSizeAtPath:[self IsExistFilePath]];
            NSMutableURLRequest * mutableURLRequest = [_request mutableCopy];
            NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", downloadedBytes];
            [mutableURLRequest setValue:requestRange forHTTPHeaderField:@"Range"];
            _request = mutableURLRequest;
        }
        [[NSURLCache sharedURLCache] removeCachedResponseForRequest:_request];
        _operation = [[AFHTTPRequestOperation alloc] initWithRequest:_request] ;
        __block typeof(_operation)myOperation = _operation;
        [_operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:[self IsExistFilePath] append:YES]];
        [myOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            
            //            //显示下载百分比
            CGFloat present = (CGFloat)(totalBytesRead +downloadedBytes) / (totalBytesExpectedToRead + downloadedBytes) ;
            NSString * value = [NSString stringWithFormat:@"%.f%%", present * 100];
            self.playLabel.text = value;
        }];
        
        //下载成功的回调
        [myOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             NSString * str = [NSString stringWithFormat:@"<<%@>>已缓存完成",_model.title];
             //下载成功的提示框
             UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:str  delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
             [alertView show];
             [_playButton setTitle:@"已缓存" forState:UIControlStateNormal];
             [[NSFileManager defaultManager] moveItemAtPath:[self IsExistFilePath] toPath:[self IsExistdownLoadFilePath] error:nil];
             
             _playButton.userInteractionEnabled = NO;
             _playButton.alpha = 0.6;
             _btnDownload.userInteractionEnabled = NO;
             _btnDownload.alpha = 0.4;
             
             
             [self.dataArray addObject:_model];
             
             
             //  将缓存好的信息  存在数据库
             [self make_modelToDownloadDatabase];
             
             
             
         } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
         }];
        //开启任务, 必须是手动开启
        [_operation start];
    }else{
        [_playButton setTitle:@"缓存" forState:UIControlStateNormal];
        [_operation cancel];
        _operation = nil;
        [self removeFileAtPath:_model.title];
        _playLabel.alpha = 0;
    }
}
//查询数据库，判断是否收藏
- (void)isCollection
{
    //判断是否单开数据库
    [self isWithOpenDataBase];
    
    //  查询数据库
    FMResultSet *rs = [_db executeQuery:@"SELECT * FROM Collection where title = ?",_model.title];
    while ([rs next])  //  类库中的方法  循环查询
    {
        [_collectionButton setImage:[UIImage imageNamed:@"yishoucang"] forState:UIControlStateNormal];
        
        
        
        _isCollect = YES;
        return;
    }
    _isCollect = NO;
    
    [_collectionButton setImage:[UIImage imageNamed:@"iconfont-weishoucang"] forState:UIControlStateNormal];
    
}
//查询数据库，判断是否下载
- (BOOL)isWithDownLoad
{
    //判断是否单开数据库
    [self isWithOpenDataBase];
    
    //查询数据库
    FMResultSet *rs = [_db executeQuery:@"SELECT * FROM DOWNLOAD WHERE TITLE = ?", _model.title];
    while ([rs next])
    {
        return YES;
    }
    return NO;
}

#pragma park - 判断是否下载到本地
- (void)isDownload
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //如果已经下载
    if ([self isWithDownLoad] == YES)
    {
        _playButton.userInteractionEnabled = NO;
        _playButton.alpha = 0.6;
        _btnDownload.userInteractionEnabled = NO;
        _btnDownload.alpha = 0.4;
    }
    else
    {
        if([fileManager fileExistsAtPath:[self IsExistFilePath]])
        {
            [_playButton setTitle:@"取消缓存" forState:UIControlStateNormal];
            _btnDownload.userInteractionEnabled = YES;
            _btnDownload.alpha = 1;
            _playButton.userInteractionEnabled = YES;
            _playButton.alpha = 1;
        }else{
            [_playButton setTitle:@"缓存" forState:UIControlStateNormal];
            _btnDownload.userInteractionEnabled = YES;
            _btnDownload.alpha = 1;
            _playButton.userInteractionEnabled = YES;
            _playButton.alpha = 1;
        }
    }
    
    //    if ([fileManager fileExistsAtPath:[self IsExistdownLoadFilePath]])
    //    { //  如果本地存在,目的是让下载按钮变成灰色,无法点击
    //
    //        [_playButton setTitle:@"已缓存" forState:UIControlStateNormal];
    //        _playButton.userInteractionEnabled = NO;
    //        _playButton.alpha = 0.6;
    //        _btnDownload.userInteractionEnabled = NO;
    //        _btnDownload.alpha = 0.4;
    //    }
    //    else
    //    {
    //        if([fileManager fileExistsAtPath:[self IsExistFilePath]])
    //        {
    //            [_playButton setTitle:@"取消缓存" forState:UIControlStateNormal];
    //            _btnDownload.userInteractionEnabled = YES;
    //            _btnDownload.alpha = 1;
    //            _playButton.userInteractionEnabled = YES;
    //            _playButton.alpha = 1;
    //        }else{
    //            [_playButton setTitle:@"缓存" forState:UIControlStateNormal];
    //            _btnDownload.userInteractionEnabled = YES;
    //            _btnDownload.alpha = 1;
    //            _playButton.userInteractionEnabled = YES;
    //            _playButton.alpha = 1;
    //        }
    //    }
}



#pragma park - 删除本地正在缓存的视频
- (void)removeFileAtPath:(NSString *)filename {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString * tmp = [NSHomeDirectory() stringByAppendingString:@"/Library"];
    NSString * _modelPath = [tmp stringByAppendingString:@"/Caches"];
    NSString *delelteFilePath = [_modelPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",filename]];
    [fileManager removeItemAtPath:delelteFilePath error:nil];
}

#pragma park - 删除本地已经下载好的视频
- (void)deleteFileAtPath:(NSString *)filename {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString * tmp = [NSHomeDirectory() stringByAppendingString:@"/tmp"];
    NSString * _modelPath = [tmp stringByAppendingString:@"/_model"];
    NSString *delelteFilePath = [_modelPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",filename]];
    [fileManager removeItemAtPath:delelteFilePath error:nil];
    
}

#pragma park - 将_model存储到缓存数据库中
- (void)make_modelToDownloadDatabase
{
    [self isWithOpenDataBase];
    
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS Download (Category text, CoverBlurred text, CoverForDetail text, CoverForFeed text, CoverForSharing text, Date integer, Description text, Duration integer, ID integer,Idx integer, PlayUrl text, RawWebUrl text, Title text, WebUrl text)"];
    NSNumber *duration = [NSNumber numberWithInteger:_model.duration];
    NSNumber *ID = [NSNumber numberWithInteger:_model.ID];
    NSNumber *idx = [NSNumber numberWithInteger:_model.idx];
    NSNumber *date = [NSNumber numberWithInteger:_model.date];
    
    [_db executeUpdate:@"INSERT INTO Download (Category, CoverBlurred,CoverForDetail,CoverForFeed,CoverForSharing,Date,Description,Duration,ID,Idx,PlayUrl,RawWebUrl,Title,WebUrl) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",_model.category,_model.coverBlurred,_model.coverForDetail,_model.coverForFeed,_model.coverForSharing,date,_model.Description,duration,ID,idx,_model.playUrl,_model.rawWebUrl,_model.title,_model.webUrl];
}

//下载路径
- (NSString *)IsExistFilePath
{
    NSString * cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
    
    NSString * filePath = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",_model.title]];
    NSLog(@"-----------%@",_model.title);
    return filePath;
}

//下载完成的路径
- (NSString *)IsExistdownLoadFilePath
{
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    NSString * tmp = [NSHomeDirectory() stringByAppendingString:@"/tmp"];
    
    NSString * _modelPath = [tmp stringByAppendingString:@"/_model"];
    if (![fileManager fileExistsAtPath:_modelPath]) {
        [fileManager createDirectoryAtPath:_modelPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString * downLoadFinished = [_modelPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",_model.title]];
    return downLoadFinished;
}
//计算缓存路径的大小
- (unsigned long long)fileSizeAtPath:(NSString *)fileAbsolutePath
{
    signed long long fileSize = 0;
    NSFileManager * fileManager = [NSFileManager new];
    if ([fileManager fileExistsAtPath:fileAbsolutePath]) {
        NSError *error = nil;
        NSDictionary *fileDict = [fileManager attributesOfItemAtPath:fileAbsolutePath error:&error];
        if (!error && fileDict) {
            fileSize = [fileDict fileSize];
        }
    }
    return fileSize;
}


#pragma park - 将model存储到数据库中
- (void)makeModelToDatabase
{
    NSNumber *duration = [NSNumber numberWithInteger:_model.duration];
    NSNumber *ID = [NSNumber numberWithInteger:_model.ID];
    NSNumber *idx = [NSNumber numberWithInteger:_model.idx];
    NSNumber *date = [NSNumber numberWithInteger:_model.date];
    
    [_db executeUpdate:@"INSERT INTO Collection (Category, CoverBlurred,CoverForDetail,CoverForFeed,CoverForSharing,Date,Description,Duration,ID,Idx,PlayUrl,RawWebUrl,Title,WebUrl) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",_model.category,_model.coverBlurred,_model.coverForDetail,_model.coverForFeed,_model.coverForSharing,date,_model.Description,duration,ID,idx,_model.playUrl,_model.rawWebUrl,_model.title,_model.webUrl];
}

- (void)deleteModelFromDatabase
{
    //  按title 查询删除
    NSString *str = _model.title;
    //  删除数据库的方法
    NSString *deleteStr = [NSString stringWithFormat:@"DELETE fROM %@ where %@ = '%@'",@"Collection",@"Title",str];
    [_db executeUpdate:deleteStr];
}

- (void)createFirstView
{
    _downsideView = [[DownSideView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT / 2, SCREEN_WIDTH, SCREEN_HEIGHT / 2)];
    
    _downsideView.model = _model;
    
    _downsideView.firstView.alpha = 1;
    
    [self.view addSubview:_downsideView];
}


@end
